﻿<?php

include("class.base.php");
if (!$sess = sisse_logitud()) { header("Location: index.php"); die(); }

if (!$minu_grupi_oigused = grupi_oigused($sess)) {
	header("Location: index.php"); die();
}
if ($minu_grupi_oigused < 2) {
	header("Location: index.php"); die();
}

$minuLemmikud = mysql_query("SELECT * FROM lemmikud WHERE lisaja=".$sess["id"]);
$lemmikud = array();
while ($lemmik = mysql_fetch_array($minuLemmikud)) {
	array_push($lemmikud, $lemmik["tabel"]."-".$lemmik["vali"]);
}

$tabel1 = kriips($_GET["t"], 0);
$xtabel = trim(htmlspecialchars($_GET["t"], ENT_QUOTES));
$t_id = htmlspecialchars($_GET["id"], ENT_QUOTES);
if (!lang_exists($t_id)) { $langTable = 0; }
else { $langTable = 1; }

$pealkiri1 = $lang["muuda"]." ".$tabel1;
$allTables = get_tables();
$publicTables = getPublicTables();
$infoTables = getInfoTables();

if (in_array($xtabel, $allTables)) {
	$sqlB = "SELECT * FROM ".$xtabel." WHERE id='".$t_id."'";
	if ($paring = mysql_query($sqlB)) {
		$rida = mysql_fetch_array($paring);
		if ($minu_grupi_oigused < 3 and $rida["lisaja"] != $sess["id"]) {
			header("Location: index.php"); die();
		}
		
		$excludes = excludes(0);
		if ($langTable == 1) { $excludes = array(); }
		$must_have_fields = get_must_have_columns($xtabel);
		$result = mysql_query("SHOW COLUMNS FROM ".$xtabel);

		if (isset($_POST["submit_muuda"])) { //tahetakse muuta kirjet andmebaasis
			$lisatudKeel = "";
			while ($columns = mysql_fetch_array($result)) {
				$n = trim(htmlspecialchars($_POST[$columns[0]], ENT_QUOTES)); //eemalda whitespace'd ja muuda ära erisümbolid
				if (!in_array($columns[0], $excludes) and
					in_array($columns[0], $must_have_fields) and
					$n == "") {
						$viga = kriips($columns[0])." ".$lang["on_kohustuslik"]; break;
				}
				if ($langTable == 1) { $sql .= $columns[0]."='".$n."',"; }
				elseif (!in_array($columns[0], $excludes)) { //et siis igasugu jama ei taha me päringusse
					$tyyp = $columns[1]; //otsitava andme tüüp
					$tyyp = explode("(", $tyyp);
					$tyyp = $tyyp[0]; //int, varchar, date, datetime etc
					if ($tyyp == "date") {
						if (!in_array($columns[0], $must_have_fields) and $n == "") {
							$sql .= $columns[0]."=NULL,";
						}
						elseif ($kuup = date_to_mysql($n)) {
							$sql .= $columns[0]."='".$kuup."',";
						}
					}
					elseif ($columns[0] == "kestus") {
						if (!in_array($columns[0], $must_have_fields) and $n == "") {
							$sql .= $columns[0]."=NULL,";
						}
						else {
							$tykid = array_reverse(explode(":", $n));
							$korda = 1;
							$secs = 0;
							foreach ($tykid as $tykk) {
								$secs = $secs + $tykk*$korda;
								$korda = $korda*60;
							}
							$sql .= "kestus='".$secs."',";
						}
					}
					elseif ($columns[0] == "keel" && $xtabel != "materjal_keel") { $lisatudKeel = $n; }
					else {
						if (!in_array($columns[0], $must_have_fields) and $n == "") {
							$sql .= $columns[0]."=NULL,";
						}
						else {
							$sql .= $columns[0]."='".$n."',";
						}
					}
				}
			}
			$sql = rtrim($sql, ",");
			if (!isset($viga)) {
				if (mysql_query("UPDATE ".$xtabel." SET ".$sql." WHERE id='".$t_id."'")) {
					if ($lisatudKeel) {
						mysql_query("INSERT INTO materjal_keel SET keel='".$lisatudKeel."', materjal='".$xtabel."', materjal_id='".$t_id."'");
					}
					mysql_query("INSERT INTO logi SET ip='".$_SERVER["REMOTE_ADDR"]."', syndmus='<a href=\'naita.php?t=kasutaja&id=".$sess["id"]."\'>".$sess["email"]."</a> muutis <a href=\'naita.php?t=".$xtabel."&id=".$t_id."\'>".kriips($xtabel)." id ".$t_id."</a>', andmebaasi_lisatud=NOW()");
					$muutmineOnnestus = 1;
					//muuda arhiivinumber ära serveri kõhus
					if (isset($_POST["arhiivinumber"])) {
						$uusArhNr = htmlspecialchars($_POST["arhiivinumber"], ENT_QUOTES);
						$uusArhNr1 = explode("-",substr($uusArhNr, 0, -1));
						$uusSarjaTahis = trim(str_replace(range(0,9),"",$uusArhNr1[0]));
						if ($rida["arhiivinumber"] != $uusArhNr) {
							if ($xtabel == "audio_trakk" || $xtabel == "audio") {
								if ($xtabel == "audio_trakk") {
									$sari = mysql_fetch_array(mysql_query("SELECT * FROM audio WHERE id=".$rida["audio"]));
								}
								else {
									$sari["sari"] = $rida["sari"];
								}
								$sarjaParing = mysql_fetch_array(mysql_query("SELECT * FROM sari WHERE id=".$sari["sari"]));
								$eemaldaSari = explode($sarjaParing["sarja_tahis"], $rida["arhiivinumber"]);
								$filedir = AUDIO_PATH.$sarjaParing["sarja_tahis"]."_WAV/".$sarjaParing["sarja_tahis"].substr($eemaldaSari[1], 0, 2);
								$publicDirs = array("wav_audio", "mp3_audio");
							}
							elseif ($xtabel == "foto" || $xtabel == "fotoalbum") {
								if ($xtabel == "foto") {
									$album = mysql_fetch_array(mysql_query("SELECT * FROM fotoalbum WHERE id=".$rida["fotoalbum"]));
								}
								else {
									$album["sari"] = $rida["sari"];
								}
								$sarjaParing = mysql_fetch_array(mysql_query("SELECT * FROM sari WHERE id=".$album["sari"]));
								$filedir = PHOTO_PATH.$sarjaParing["sarja_tahis"]."/".$album["arhiivinumber"];
								$publicDirs = array("jpeg_img");
							}
							elseif ($xtabel == "kasikiri") {
								$sarjaParing = mysql_fetch_array(mysql_query("SELECT * FROM sari WHERE id=".$rida["sari"]));
								$filedir = KASIKIRI_PATH.$sarjaParing["sarja_tahis"]."/".$rida["arhiivinumber"];
								$publicDirs = array("jpeg_img", "pdf_doc", "zip_archive");
							}
							if (is_dir($filedir)) {
								if ($xtabel == "kasikiri" || $xtabel == "audio" || $xtabel == "fotoalbum") {
									$finalNewFileDir = str_replace($rida["arhiivinumber"], $uusArhNr, $filedir);
									if ($uusSarjaTahis != $sarjaParing["sarja_tahis"]) {
										$finalNewFileDir = str_replace($sarjaParing["sarja_tahis"], $uusSarjaTahis, $finalNewFileDir);
									}
									if ($xtabel == "audio_trakk" || $xtabel == "audio") {
										$vanaKaheKohaline = substr($eemaldaSari[1], 0, 2);
										$eemaldaSari = explode($uusSarjaTahis, $uusArhNr);
										$uusKaheKohaline = substr($eemaldaSari[1], 0, 2);
										if ($vanaKaheKohaline != $uusKaheKohaline) {
											$finalNewFileDir = str_replace($uusSarjaTahis.'/'.$vanaKaheKohaline, $uusSarjaTahis.'/'.$uusKaheKohaline, $finalNewFileDir);
										}
									}
								}
								else {
									$handler = opendir($filedir);
									while ($file = readdir($handler)) {
										if ($file != "." and $file != "..") {
											if (stristr($file, $rida["arhiivinumber"]) && !isset($finalOrigFile)) {
												$finalOrigFile = $filedir."/".$file;
												$finalOrigFileName = $file;
											}
											if (stristr($file, $uusArhNr) && !isset($finalNewFile)) {
												$finalNewFile = $filedir."/".$file;
											}
										}
									}
									closedir($handler);
								}
								if (isset($finalNewFile) && isset($finalOrigFile) || (($xtabel == "kasikiri" || $xtabel == "audio" || $xtabel == "fotoalbum") && is_dir($finalNewFileDir))) {
									mysql_query("INSERT INTO logi SET ip='".$_SERVER["REMOTE_ADDR"]."', syndmus='Materjali <a href=\'naita.php?t=".$xtabel."&id=".$t_id."\'>".kriips($xtabel)." id ".$t_id."</a> failinime serveris ei saanud muuta, sest sama arhiivinumbriga fail on juba olemas', andmebaasi_lisatud=NOW()");
									$muutmineOnnestus = 0;
								}
								elseif (isset($finalOrigFile)) {
									if ($xtabel == "foto") {
										$filedir = str_relpace($rida["arhiivinumber"], $uusArhNr, $filedir);
									}
									$finalNewFileName = $filedir."/".str_replace($rida["arhiivinumber"], $uusArhNr, $finalOrigFileName);
									if ($uusSarjaTahis != $sarjaParing["sarja_tahis"]) {
										$finalNewFileName = str_replace($sarjaParing["sarja_tahis"], $uusSarjaTahis, $finalNewFileName);
									}
									if ($xtabel == "audio_trakk" || $xtabel == "audio") {
										$vanaKaheKohaline = substr($eemaldaSari[1], 0, 2);
										$eemaldaSari = explode($uusSarjaTahis, $uusArhNr);
										$uusKaheKohaline = substr($eemaldaSari[1], 0, 2);
										if ($vanaKaheKohaline != $uusKaheKohaline) {
											$finalNewFileName = str_replace($uusSarjaTahis.$vanaKaheKohaline, $uusSarjaTahis.$uusKaheKohaline, $finalNewFileName);
										}
									}
									$finalNewFileDir = array_reverse(explode("/", $finalNewFileName));
									unset($finalNewFileDir[0]);
									$finalNewFileDir = implode("/", array_reverse($finalNewFileDir));
									if (!is_dir($finalNewFileDir)) {
										mkdir($finalNewFileDir, 0777, true);
									}
									rename($finalOrigFile, $finalNewFileName);
									foreach ($publicDirs as $publicDir) {
										$handler = opendir($publicDir);
										while ($file = readdir($handler)) {
											if ($file != "." and $file != "..") {
												if (stristr($file, $rida["arhiivinumber"])) {
													rename($publicDir."/".$file, $publicDir."/".str_replace($rida["arhiivinumber"], $uusArhNr, $file));
													break;
												}
											}
										}
										closedir($handler);
									}
									mysql_query("INSERT INTO logi SET ip='".$_SERVER["REMOTE_ADDR"]."', syndmus='Materjali <a href=\'naita.php?t=".$xtabel."&id=".$t_id."\'>".kriips($xtabel)." id ".$t_id."</a> failinimi serveris on muudetud', andmebaasi_lisatud=NOW()");
								}
								elseif (($xtabel == "kasikiri" || $xtabel == "audio" || $xtabel == "fotoalbum") && !is_dir($finalNewFileDir)) {
									$handler = opendir($filedir);
									while ($file = readdir($handler)) {
										if ($file != "." and $file != "..") {
											if (stristr($file, $rida["arhiivinumber"])) {
												rename($filedir."/".$file, $filedir."/".str_replace($rida["arhiivinumber"], $uusArhNr, $file));
											}
										}
									}
									closedir($handler);
									rename($filedir, $finalNewFileDir);
									foreach ($publicDirs as $publicDir) {
										$handler = opendir($publicDir);
										while ($file = readdir($handler)) {
											if ($file != "." and $file != "..") {
												if (stristr($file, $rida["arhiivinumber"])) {
													rename($publicDir."/".$file, $publicDir."/".str_replace($rida["arhiivinumber"], $uusArhNr, $file));
												}
											}
										}
										closedir($handler);
									}
									mysql_query("INSERT INTO logi SET ip='".$_SERVER["REMOTE_ADDR"]."', syndmus='Materjali <a href=\'naita.php?t=".$xtabel."&id=".$t_id."\'>".kriips($xtabel)." id ".$t_id."</a> failinimi serveris on muudetud', andmebaasi_lisatud=NOW()");
								}
							}
						}
					}
					if (lang_exists($t_id)) {
						header("Location: haldus.php?keelte_haldus=1"); die();
					} else { header("Location: naita.php?t=".$xtabel."&id=".$t_id."&muuda=".$muutmineOnnestus); die(); }
				}
				else {
					$viga = mysql_error();
				}
			}
		} //taheti muuta kirjet andmebaasis

		$sisu ="
			<form action='' method='POST'>
				<table class='colspace'>";
		$r = $rida;
		$result = mysql_query("SHOW COLUMNS FROM ".$xtabel);
		while ($columns = mysql_fetch_array($result)) { //genereeritakse html vorm
			if (!in_array($columns[0], $excludes)) {
				if (isset($_POST[$columns[0]])) { $n = $_POST[$columns[0]]; }
				else { $n = $r[$columns[0]]; }
				$leiatyyp = explode("(", $columns[1]);
				$tyyp = $leiatyyp[0];
				if ($columns[2] == "NO") { $tarn = "*"; } else { $tarn = ""; }
				$sisu .= "<tr><td>".kriips($columns[0])." ".$tarn."</td><td>";
				if ($langTable == 1) { $sisu .= "<textarea name='".$columns[0]."' cols='25' rows='3'>".$n."</textarea>".pretty_filetype($tyyp); }
				elseif (in_array($columns[0], $allTables)) {
					$shows = get_must_show_columns($columns[0]);
					$kysi_teisest_tabelist = mysql_query("SELECT * FROM ".$columns[0]." ORDER BY ".$shows[0]);
					$sisu .= "<select name='".$columns[0]."' width='300' style='width: 300px'><option value=''></option>";
					while ($rida = mysql_fetch_array($kysi_teisest_tabelist)) {
						if ($rida["id"] == $n) { $selectedF = " selected='selected'"; } else { $selectedF = ""; }
						if ($selectedF == "" && in_array($columns[0], $infoTables)) {
							if (ucfirst_utf8($n) == $rida["id"]) { $selectedF = " selected='selected'"; } else { $selectedF = ""; }
						}
						$sisu .= "
							<option value='".$rida["id"]."'".$selectedF.">";
						foreach ($shows as $show) { $sisu .= " ".$rida[$show]; }
						$sisu .= "</option>";
					}
					$sisu .= "</select>";
					$sisu .= " <a href='lisa.php?t=".$columns[0]."&u=".$xtabel."&id=".$t_id."&ref=muuda'>".$lang["lisa_uus"]."</a>";
				}
				elseif ($columns[0] == "ressursi_tyyp") {
					$n2 = "ressursi_tyyp".$n; $$n2 = " selected='selected'";
					$sisu .= "
					<select name='ressursi_tyyp'>
						<option value=''></option>
						<option value='1'".$ressursi_tyyp1.">".$lang["fyysiline"]."</option>
						<option value='2'".$ressursi_tyyp2.">".$lang["digitaalne"]."</option>
					</select>";
				}
				elseif ($columns[0] == "fyysiliselt_olemas") {
					$n2 = "fyysiliselt_olemas".$n; $$n2 = " selected='selected'";
					$sisu .= "
					<select name='fyysiliselt_olemas'>
						<option value=''></option>
						<option value='1'".$fyysiliselt_olemas1.">".$lang["olemas"]."</option>
						<option value='2'".$fyysiliselt_olemas2.">".$lang["kadunud"]."</option>
						<option value='3'".$fyysiliselt_olemas3.">".$lang["laenatud"]."</option>
					</select>";
				}
				elseif ($columns[0] == "digitaalselt_olemas") {
					$n2 = "digitaalselt_olemas".$n; $$n2 = " selected='selected'";
					$sisu .= "
					<select name='digitaalselt_olemas'>
						<option value=''></option>
						<option value='1'".$digitaalselt_olemas1.">".$lang["jah"]."</option>
						<option value='2'".$digitaalselt_olemas2.">".$lang["ei"]."</option>
					</select>";
				}
				elseif ($columns[0] == "oigused") {
					$n2 = "oigused".$n; $$n2 = "selected='selected'";
					$sisu .= "
						<select name='oigused'>
							<option value='avalik'".$oigusedavalik.">".$lang["avalik"]."</option>
							<option value='mitteavalik'".$oigusedmitteavalik.">".$lang["mitteavalik"]."</option>
						</select>";
				}
				elseif ($columns[0] == "materjal") {
					$sisu .= "
						<select name='materjal' onchange=\"generate_list(this.value, '".$xtabel."');\">";
					foreach ($publicTables as $value) {
						if ($n == $value) { $selected = " selected='selected'"; } else { $selected = ""; }
						$sisu .= "
							<option value='".$value."'".$selected.">".kriips($value)."</option>";
					}
					$sisu .= "</select>";
				}
				elseif ($columns[0] == "materjal_id") {
					$must_have_columns = get_must_show_columns($r["materjal"]);
					$paring = mysql_query("SELECT * FROM ".$r["materjal"]." ORDER BY ".$must_have_columns[0]);
					$sisu .= "<span id='uus_".$xtabel."_".$xtabel."'><select name='materjal_id' width='300' style='width: 300px'>";
					while ($rida = mysql_fetch_array($paring)) {
						if ($n == $rida["id"]) { $selected = " selected='selected'"; } else { $selected = ""; }
						$sisu .= "
						<option value='".$rida["id"]."'".$selected.">";
						foreach ($must_have_columns as $value) {
							if ($value == "kestus") {
								$sisu .= pretty_length($rida[$value])." ";
							}
							else {
								$sisu .= $rida[$value]." ";
							}
						}
						$sisu .= "</option>";
					}
					$sisu .= "</select></span>";
				}
				elseif ($columns[0] == "kestus") {
					$sisu .= "<input type='text' name='kestus' value='".pretty_length($n)."'> numbrid [TT:][MM:]SS";
				}
				elseif ($columns[0] == "materjali_tyyp") {
					$sisu .= "
						<select name='materjali_tyyp' onchange=\"ab('".$xtabel.$u."');\">";
					foreach ($publicTables as $public_table) {
						if ($n == $public_table) { $selected = " selected='selected'"; } else { $selected = ""; }
						$sisu .= "<option value='".$public_table."'".$selected.">".kriips($public_table)."</option>";
					}
					$sisu .= "</select>";
				}
				elseif ($tyyp == "text") { $sisu .= "<textarea name='".$columns[0]."' cols='25' rows='3'>".$n."</textarea>".pretty_filetype($tyyp); }
				elseif ($tyyp == "date") { $sisu .= "<input type='text' name='".$columns[0]."' value='".date_to_est($n)."'>".pretty_filetype($tyyp); }
				else { $sisu .= "<input type='text' name='".$columns[0]."' value='".$n."'>".pretty_filetype($tyyp); }
				$sisu .= "</td></tr>";
			}
		} //genereeriti html vorm
		$sisu .="
				<tr><td></td><td><input type='submit' name='submit_muuda' value='".$lang["muuda"]." ".$tabel1."'></td></tr>
				</table>
			</form>";
	} else { $viga = $lang["tabeli_kirje_valimata_voi_kirjet_pole_olemas"]; }
} else { $viga = $lang["tabel_valimata_voi_tabelit_pole_olemas"]; }
include("kujundus.php");
?>
